package top.codecrab.eblog.common.response;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class R {

    private int status;

    private String msg;

    private Object data;

    private String action;

    public R(int status, String msg, Object data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    public static R ok() {
        return new R(0, "操作成功", null);
    }

    public static R ok(Object data) {
        return new R(0, "操作成功", data);
    }

    public static R ok(String msg, Object data) {
        return new R(0, msg, data);
    }

    @SuppressWarnings("unchecked")
    public R put(String key, Object val) {
        if (data == null) {
            data = new HashMap<String, Object>();
        }

        if (ObjectUtil.isBasicType(data) || data instanceof String || data instanceof Collection<?>) {
            return this;
        }

        if (!(data instanceof Map<?, ?>)) {
            data = BeanUtil.beanToMap(data);
        }

        Map<String, Object> map = (Map<String, Object>) data;
        map.put(key, val);
        return this;
    }

    public static R fail(String msg) {
        return new R(-1, msg, null);
    }

    /**
     * 指定操作成功后的返回路径
     */
    public R action(String action) {
        this.setAction(action);
        return this;
    }
}
